package com.demo.modules.word.common.utils;

import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

/**
 * @author MyPC
 */
@Component
public class StrUtil {

    public static byte[] compressByte(String str) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DeflaterOutputStream gzip = new DeflaterOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        return out.toByteArray();
    }

    public static String decompressByte(byte[] compressed) throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(compressed);
        InflaterInputStream inflater = new InflaterInputStream(in);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inflater.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.close();
        return out.toString();
    }

    public static String compress(String input) {
        StringBuilder sb = new StringBuilder();
        int count = 1;
        for (int i = 0; i < input.length(); i++) {
            if (i + 1 < input.length() && input.charAt(i) == input.charAt(i + 1)) {
                count++;
            } else {
                sb.append(count);
                sb.append(input.charAt(i));
                count = 1;
            }
        }
        return sb.toString();
    }

    public static String decompress(String input) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < input.length(); i += 2) {
            int count = Character.getNumericValue(input.charAt(i));
            char c = input.charAt(i + 1);
            for (int j = 0; j < count; j++) {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
